#!/usr/bin/env bash

set -eu

export PATH="$SNAP/usr/sbin:$SNAP/usr/bin:$SNAP/sbin:$SNAP/bin:$PATH"
ARCH="$($SNAP/bin/uname -m)"
export LD_LIBRARY_PATH="$SNAP/lib:$SNAP/usr/lib:$SNAP/lib/$ARCH-linux-gnu:$SNAP/usr/lib/$ARCH-linux-gnu"
export OPENSSL_CONF="/snap/microk8s/current/etc/ssl/openssl.cnf"
export IN_SNAP_LD_LIBRARY_PATH="$SNAP/lib:$SNAP/usr/lib:$SNAP/lib/$ARCH-linux-gnu:$SNAP/usr/lib/$ARCH-linux-gnu"
export PYTHONNOUSERSITE=false

source $SNAP/actions/common/utils.sh

if [ -e ${SNAP_DATA}/var/lock/clustered.lock ]
then
  echo "This MicroK8s deployment is acting as a node in a cluster. Please use the microk8s add-node on the master."
  exit 1
fi

if [ -e  "$SNAP_DATA/args/cni-network/cni.yaml.disabled" ] && [ -e "$SNAP_DATA/args/cni-network/05-cilium-cni.conf" ] ; then 
  echo "Cilium is enabled and is not suitable for multi node clusters."
  exit 1
fi

if echo "$*" | grep -q -- 'help'; then
  # Call add_token.py help
  LD_LIBRARY_PATH=$IN_SNAP_LD_LIBRARY_PATH ${SNAP}/usr/bin/python3 ${SNAP}/scripts/cluster/add_token.py --help
  exit 0
fi

exit_if_no_permissions

subject=$(openssl x509 -sha256 -days 365 -noout -subject -in "$SNAP_DATA/certs/ca.crt")
if [[ $subject == *"127.0.0.1"* ]]; then
  echo "Clustering requires a fresh MicroK8s installation. Reinstall with:"
  echo "sudo snap remove microk8s"
  echo "sudo snap install microk8s --classic"
  exit 1
fi

exit_if_stopped

if [ ! -f "$SNAP_DATA/credentials/cluster-tokens.txt" ]; then
  touch $SNAP_DATA/credentials/cluster-tokens.txt 
fi

if getent group microk8s >/dev/null 2>&1
then
  chgrp microk8s $SNAP_DATA/credentials/cluster-tokens.txt || true
fi

# Use python's built-in (3.6+) secrets generator to produce the token.
token="$(LD_LIBRARY_PATH=$IN_SNAP_LD_LIBRARY_PATH ${SNAP}/usr/bin/python3 ${SNAP}/scripts/cluster/add_token.py $@)"

port="25000"
if grep -e port "${SNAP_DATA}"/args/cluster-agent &> /dev/null
then
  port=$(cat "${SNAP_DATA}"/args/cluster-agent | "$SNAP"/usr/bin/gawk '{print $2}')
fi

default_ip="$(get_default_ip)"
all_ips="$(get_ips)"

check=$(openssl x509 -in "$SNAP_DATA"/certs/server.crt -outform der | sha256sum | cut -d' ' -f1 | cut -c1-12)

echo "From the node you wish to join to this cluster, run the following:"
echo "microk8s join ${default_ip}:$port/${token}/${check}"
echo ""
echo "If the node you are adding is not reachable through the default interface you can use one of the following:"
for addr in $(echo "${all_ips}"); do
  if ! [[ $addr == *":"* ]]; then
    echo " microk8s join ${addr}:$port/${token}/${check}"
  fi
done
